<template>
  <paneHead></paneHead>
  <div class="btns">
    <el-button :icon="Plus" @click="dialogFormVisable = true" type="primary"
      >新增</el-button
    >
  </div>
  <el-table :data="tableData.list" style="width: 100%">
    <el-table-column prop="id" label="id"></el-table-column>
    <el-table-column prop="name" label="昵称"></el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="open(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="pagination-info">
    <el-pagination
      v-model:current-page="paginationData.pageNum"
      :page-size="paginationData.pageSize"
      layout="total, prev, pager, next"
      :total="tableData.list.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
    v-model="dialogFormVisable"
    :before-close="beforeClose"
    title="添加权限"
    width="500"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      label-position="left"
      :model="form"
      :rules="rules"
    >
      <el-form-item v-show="false" prop="id">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请填写权限名称"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="permissions">
        <el-tree
          :data="permissionData"
          style="max-width: 600px"
          show-checkbox
          node-key="id"
          :default-checked-keys="defaultKeys"
          :default-expanded-keys="[2]"
          ref="treeRef"
          @check="handleTreeCheck"
        ></el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm(formRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { userGetmenu, userSetmenu, menuSelectlist } from "../../../api/group";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

// 数据定义
const dialogFormVisable = ref(false);
const form = reactive({
  id: "",
  name: "",
  permissions: [],
});
const defaultKeys = ref([4, 5]);
const treeRef = ref();
const permissionData = ref([]);
const formRef = ref();
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 先定义验证函数（确保在rules之前）
const validatePermissions = (rule, value, callback) => {
  const checkedKeys = treeRef.value?.getCheckedKeys() || [];
  if (checkedKeys.length === 0) {
    callback(new Error("请至少选择一项权限"));
  } else {
    callback();
  }
};

// 后定义rules（确保能访问到validatePermissions）
const rules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入权限名称" }],
  permissions: [{ validator: validatePermissions, trigger: "change" }],
});

// 方法定义
const handleTreeCheck = () => {
  form.permissions = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ];
};

const beforeClose = () => {
  dialogFormVisable.value = false;
  // 重置表单
  formRef.value.resetFields();
  // 清空表单数据
  form.permissions = [];
  // 重置树选择
  treeRef.value.setCheckedKeys(defaultKeys.value);
};

const confirm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      const checkedKeys = treeRef.value.getCheckedKeys();
      const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();

      userSetmenu({
        name: form.name,
        permissions: JSON.stringify([...checkedKeys, ...halfCheckedKeys]),
        id: form.id,
      }).then(({ data }) => {
        ElMessage.success("提交成功");

        beforeClose();
        getListData();
      });
    }
  });
};
// table列表数据
const tableData = reactive({ list: [] }); // 初始化响应式对象
const handleSizeChange = (val) => {
  paginationData.pageSize = val;
  getListData();
};
const handleCurrentChange = (val) => {
  paginationData.pageNum = val;
  getListData();
};
//请求列表数据
const getListData = () => {
  menuSelectlist(paginationData).then(({ data }) => {
    tableData.list = data.data;
  });
};
// 打开编辑弹窗
const open = (rowData) => {
  dialogFormVisable.value = true;
  //弹窗打开form是异步操作
  nextTick(() => {
    if (rowData) {
      Object.assign(form, {
        id: rowData.id,
        name: rowData.name,
        permissions: rowData.permissions,
      });
      treeRef.value.setCheckedKeys(rowData.permissions);
    }
  });
};
// 生命周期
onMounted(() => {
  userGetmenu().then(({ data }) => {
    permissionData.value = data.data;
    nextTick(() => {
      treeRef.value?.setCheckedKeys(defaultKeys.value);
    });
  });
  getListData();
});
</script>
<style lang="less" scoped>
.btns {
  padding: 10px 0 10px 10px;
  background-color: #fff;
}
</style>
